#include "CSDLDevice.h"
namespace age
{
	namespace kernal
	{

CSDLDevice::CSDLDevice(int width, int height, int bits, bool fullscreen)
{
	this->runApp=true;
	this->Input.Keyboard.enableKeyRepeat=true;

	unsigned int flag = SDL_OPENGL ; 
	if(fullscreen)
		flag|=SDL_OPENGL;
	if(width < 0)
		width=1;
	if(height <0 ) 
		height = 1;
	this->width = width ;
	this->height=height ;
 	SDL_Init(SDL_INIT_VIDEO);
	SDL_GL_SetAttribute( SDL_GL_RED_SIZE, 5 );
    SDL_GL_SetAttribute( SDL_GL_GREEN_SIZE, 5 );
    SDL_GL_SetAttribute( SDL_GL_BLUE_SIZE, 5 );
    SDL_GL_SetAttribute( SDL_GL_DEPTH_SIZE, 16 );
    SDL_GL_SetAttribute( SDL_GL_DOUBLEBUFFER, 1 );
	surface = SDL_SetVideoMode(width,height,bits,flag);


}

CSDLDevice::~CSDLDevice()
{
	delete surface;
	delete title ;
}

void CSDLDevice::setWindowCaption(char* title)
{
	SDL_WM_SetCaption(title,title);
	this->title=title ;

}

char*  CSDLDevice::getWindowCaption()
{
	return title; 
}

bool keyup=true;
bool CSDLDevice::run()
{
  	Input.Keyboard.key =(age::input::EKey)0;
	SDL_EnableKeyRepeat(1000,900);	
	 if(SDL_PollEvent(&event))
	{
		SDL_PumpEvents ();
		Input.Keyboard.keys = SDL_GetKeyState(NULL);
		
		if(event.type == SDL_QUIT)
		{
			this->stop();
		}

		if(event.type == SDL_KEYDOWN)
		{
			//if(Input.Keyboard.enableKeyRepeat  )
			//		keyup=true;

				if( keyup==true)
				{
					keyup=false;
					Input.Keyboard.key =(age::input::EKey)event.key.keysym.sym;
					Input.Keyboard.isKeyDown=true;
				}
				else
					Input.Keyboard.key =(age::input::EKey)0;

		}

		if(event.type == SDL_KEYUP)
		{ 
			keyup=true;
			Input.Keyboard.key = (age::input::EKey)0;
			Input.Keyboard.isKeyDown=false;
		}

		/*if(event.active.type == SDL_ACTIVEEVENT)
		{
			if(event.active.gain==1 && event.active.state == SDL_APPACTIVE )
				// our application is active
		}*/

	}
	
	
	return runApp ; 
}

void CSDLDevice::stop()
{
	runApp = false;
	SDL_Quit();
	exit(0);
}

bool CSDLDevice::isWindowActive()
{
	return SDL_GetAppState() == SDL_APPACTIVE;
}

void CSDLDevice::minimizeWindow()
{
	SDL_WM_IconifyWindow();
}



void CSDLDevice::closeDevice()
{
	SDL_FreeSurface(surface);
	SDL_Quit();
}



SMonitorInfo& CSDLDevice::getMonitorInfo()
{
	#if defined(_WIN32)
	Info.screenWidth=GetSystemMetrics(SM_CXSCREEN);
	Info.screenHeight=GetSystemMetrics(SM_CYSCREEN);
	#endif
	const SDL_VideoInfo* f = NULL;
	f = SDL_GetVideoInfo( );
	Info.bits=	f->vfmt->BitsPerPixel ; 
	delete f ;
	return Info ; 
	
}

Recti* CSDLDevice::getListModes()
{
	SDL_Rect** modes=SDL_ListModes(NULL, SDL_FULLSCREEN|SDL_HWSURFACE);
	int size=0;
	for(int i=0;modes[i];i++)
	{
		size++;
	}
	Recti r[100];
  	
	for(int i=0;i<size;++i)
	{
		r[i].x = modes[i]->x;
		r[i].y = modes[i]->y;
		r[i].width=modes[i]->w;
		r[i].height=modes[i]->h;
	}
	delete []modes ;
	return r; 
}

 
 
	} // kernal

} // age


	
	